<?php
namespace Qwadmin\Controller;

use Vendor\Tree;
use Think\Model;
header("Content-type: text/html; charset=utf-8");
class UserController extends ComController{

    private $send_offset = 600;

	/**
	 * 前台用户管理
	 * */
	public function index($sid = 0, $p = 1)
	{
	
		//获得所有公众号平台
		$platform_list = D("platform")->select();
		//获取推送的公众平台的人数
		$domain = D('platform')->field('domain')->where("put_template_id != '' and is_put = 1")->select();
		foreach($domain as $val){
			$domain_arr .= $val['domain'].',';
		}
		$domain_arr = rtrim($domain_arr, ",");
		$cond['domain'] = array('in',$domain_arr);
		$cond['subscribe'] = 1;
		$push_count = D("user")->where($cond)->count();
        //dump($push_count);die;
		$this->assign("push_count",$push_count);
		$this->assign("platform_list",$platform_list);
		
// 		//查询条件
		if(!empty($_GET["nickname"])) {
			$map["nickname"] = array("like","%".$_GET["nickname"]."%");
			$this->assign("search_name",$_GET["nickname"]);
		}
		if(!empty($_GET["domain"])){
			$map["domain"] = $_GET["domain"];
			$this->assign("domain",$_GET["domain"]);
		}
		
		$subscribe['is_stock'] = 0;
		$subscribe['is_service'] = 0;

		$subscribe_platform = D('platform')->where($subscribe)->select();
		//dump($subscribe_platform);die;
		$this->assign('subscribe',$subscribe_platform);
// 		if(!empty($_GET["other_class_id"])){
// 			$map["other_class_id"] = $_GET["other_class_id"];
// 			$this->assign("search_other_class_id",$_GET["other_class_id"]);
// 		}
		$p = $_GET["p"] ? $_GET["p"] : 1;
		
		$novel = M('user');
		$pagesize = 20;#每页数量
		$offset = $pagesize * ($p - 1);//计算记录偏移量
		
		
		$count = $novel->where($map)->count();
		$list = $novel->where($map)->order("user_id desc")->limit($offset . ',' . $pagesize)->select();
		foreach($list as $key=>$item){
			$rs = D("platform")->field("platform_name")->where("domain='".$item["domain"]."'")->find();
			$list[$key]["platform_name"] = $rs["platform_name"];
			
			//获得历史记录
			$map["open_id"] = $item["open_id"];
			$hi_rs = D("read_history")->where($map)->order($map)->order("addtime desc")->find();
			if(!empty($hi_rs))
				$list[$key]["history"] = $hi_rs["novel_name"]." ".$hi_rs["chapter"]." <a href='/Home/Novel/show/id/".$hi_rs["chapter_id"]."/novel_id/".$hi_rs["novel_id"]."'>".$hi_rs["chapter_name"]."</a>";
		}
		
		$page = new \Think\Page($count, $pagesize);
		$page = $page->show();
		$this->assign('list', $list);
		$this->assign('page', $page);
		$this->display();
	}
	
	/**
	 * 服务号推送图文信息
	 * */
	public function send_info(){
		
		set_time_limit(0);
		$url_str = $_POST['url'];
		$url_str = substr($url_str,strpos($url_str,'/Home'));
		//dump($url_str);die;
		$user_id = $_POST["user_ids"];
		
		if(!empty($user_id)){
			$map["user_id"] = array("in", $user_id);
			$map['subscribe'] = 1;
			//$map["domain"] = $_POST["domain"];
            //获取关注了的用户
			$list = D("user")->where($map)->select();
			foreach ($list as $key=>$item){
			    //新生活影音推送图文信息
				$url = 'http://'.$item["domain"].$url_str;
                $this->sendimg($item["domain"], "@".$item["nickname"]."  ".$_POST["title"], $_POST["desc"], $url, $_POST["img"], $item["open_id"]);
            }
		}else{
			$map["subscribe"] = 1;
			$list = D("user")->field("open_id,domain,nickname")->where($map)->select();
			//dump($list);die;
			//print_r($_POST);die;
			foreach ($list as $key=>$item){
				$url = 'http://'.$item["domain"].$url_str;
                $this->sendimg($item["domain"], "@".$item["nickname"]."  ".$_POST["title"], $_POST["desc"], $url, $_POST["img"], $item["open_id"]);				
				//die;
			}
		}
        addlog("推送了服务号单图文消息");
		echo "the end";
	}
	
	/**
     * 订阅号推送图文信息
     */
	public function subscribe_send_info(){
	    //dump($_POST);die;
        set_time_limit(0);
	   $platform_id = $_POST['platform_id'];
	   //文艺街拍
	   if($platform_id == '10'){

           $platform_arr = D('platform')->where("platform_id='$platform_id'")->find();
           //获取token
           if($platform_arr['out_time']>time()){
               $token = getWeChatToken($platform_arr["appid"],$platform_arr["secret"],$platform_arr["token"]);
           }else{
               $token = getWeChatToken($platform_arr["appid"],$platform_arr["secret"]);
           }
           //得到token之后再获取用户列表
           $geturl = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$token.'&next_openid=';

           $arr = $this->getopenid($geturl);
          //dump($arr);die;
          $openid_arr = $arr[0];
          foreach ($openid_arr as $openid){
              foreach($openid as $open_id){
                  $this->sendimgsubscribe($platform_id, $_POST["title"], $_POST["desc"], $_POST['url'], $_POST["img"], $open_id);
              }
          }
	        addlog("推送了文艺街拍单图文消息");
		   echo 'the  end';die;
		   //经典语语录
       }elseif ($platform_id == '11'){
		   
           $platform_arr = D('platform')->where("platform_id='$platform_id'")->find();
           //获取token
           if($platform_arr['out_time']>time()){
               $token = getWeChatToken($platform_arr["appid"],$platform_arr["secret"],$platform_arr["token"]);
           }else{
               $token = getWeChatToken($platform_arr["appid"],$platform_arr["secret"]);
           }
           //得到token之后再获取用户列表
           $geturl = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$token.'&next_openid=';

           $arr = $this->getopenid($geturl);
           //dump($arr);die;
           $openid_arr = $arr[0];
           foreach ($openid_arr as $openid){
               foreach($openid as $open_id){
                   //获取用户信息
                   /*$userinfo_url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$token.'&openid='.$open_id.'&lang=zh_CN';

                   $userinfo = weChatCurl($userinfo_url);
                   if($userinfo['nickname'] == '王溪'){
                       dump($userinfo);die;
                   }*/
					//dump($open_id);
                  $this->sendimgsubscribe($platform_id, $_POST["title"], $_POST["desc"], $_POST['url'], $_POST["img"], $open_id);
               }
           }
		   addlog("推送了经典语语录单图文消息");
		   echo 'the  end';die;
        //起点相册
       }elseif($platform_id == '12'){

           $platform_arr = D('platform')->where("platform_id='$platform_id'")->find();
           //获取token
           if($platform_arr['out_time']>time()){
               $token = getWeChatToken($platform_arr["appid"],$platform_arr["secret"],$platform_arr["token"]);
           }else{
               $token = getWeChatToken($platform_arr["appid"],$platform_arr["secret"]);
           }
           //得到token之后再获取用户列表
           $geturl = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$token.'&next_openid=';

           $arr = $this->getopenid($geturl);
           //dump($arr);die;
           $openid_arr = $arr[0];
           foreach ($openid_arr as $openid){
               foreach($openid as $open_id){
                   $this->sendimgsubscribe($platform_id, $_POST["title"], $_POST["desc"], $_POST['url'], $_POST["img"], $open_id);
               }
           }
		   addlog("推送了起点相册单图文消息");
		   echo 'the  end';die;
           //金典说说录
       }elseif ($platform_id == '13'){

           $platform_arr = D('platform')->where("platform_id='$platform_id'")->find();
           //获取token
           if($platform_arr['out_time']>time()){
               $token = getWeChatToken($platform_arr["appid"],$platform_arr["secret"],$platform_arr["token"]);
           }else{
               $token = getWeChatToken($platform_arr["appid"],$platform_arr["secret"]);
           }
           //得到token之后再获取用户列表
           $geturl = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$token.'&next_openid=';

           $arr = $this->getopenid($geturl);
           //dump($arr);die;
           $openid_arr = $arr[0];
           foreach ($openid_arr as $openid){
               foreach($openid as $open_id){
                   $this->sendimgsubscribe($platform_id, $_POST["title"], $_POST["desc"], $_POST['url'], $_POST["img"], $open_id);
               }
           }
		   addlog("推送了金典说说录单图文消息");
		   echo 'the  end';die;
       }
    }
	
	/**
     * @param $domain
     * @param $title
     * @param $description
     * @param $_url
     * @param $picurl
     * @param $open_id
     * 订阅号推送图文信息
     */
    protected function sendimgsubscribe($platform_id,$title,$description,$_url,$picurl,$open_id){

        //echo 222;die;
        $map["platform_id"] = $platform_id;
        $platform = D("platform")->where($map)->find();
        if(intval($platform["out_time"]) > time())	{
            $token = getWeChatToken($platform["appid"],$platform["secret"],$platform["token"]);
        }
        else{
            $token = getWeChatToken($platform["appid"],$platform["secret"]);
        }

        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$token";
        $data = '{
				    "touser":"'.$open_id.'",
				    "msgtype":"news",
				    "news":{
				        "articles": [
					         {
					             "title":"'.$title.'",
					             "description":"'.$description.'",
					             "url":"'.$_url.'",
					             "picurl":"'.$picurl.'"
					         }
				         ]
				    }
				}
		';
        $result = weChatCurl($url, 1, $data);
        //print_r($result);
    }
	
	/**
	 * 群发图文接口
	 * @domain 用户针对的域名,判断用户是哪个公众号的
	 * @title 图文标题
	 * @description 描述
	 * @url 连接地址
	 * @picurl 图片地址
	 * @open_id 用户OPEN_ID
	 * */
	protected function sendimg($domain,$title,$description,$_url,$picurl,$open_id){
		$map["domain"] = $domain;		
		$platform = D("platform")->where($map)->find();
		if(intval($platform["out_time"]) > time())	{
			$token = getWeChatToken($platform["appid"],$platform["secret"],$platform["token"]);
		}
		else{
			$token = getWeChatToken($platform["appid"],$platform["secret"]);
		}
		
		$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$token";
		$data = '{
				    "touser":"'.$open_id.'",
				    "msgtype":"news",
				    "news":{
				        "articles": [
					         {
					             "title":"'.$title.'",
					             "description":"'.$description.'",
					             "url":"'.$_url.'",
					             "picurl":"'.$picurl.'"
					         }
				         ]
				    }
				}
		';
		$result = weChatCurl($url, 1, $data);
	}
	
	/**
	 * 遍历推送模板信息
	 * */
	public function send_info2(){
		set_time_limit(0);
		$user_id = $_POST["user_ids"];
		//print_r($user_id);die;
		if(!empty($user_id)){
			//dump($user_id);die;
			$map["user_id"] = array("IN", $user_id);
			$map['subscribe'] = 1;
			$list = D("user")->where($map)->select();
			//dump($list);die;
			foreach ($list as $key=>$item){
				$domain = $item['domain'];
				//拼接域名
				$url = $_POST['novel_url'];
				$url_start = strpos($url,'/Home');
				$url_str = substr($url,$url_start);
				$cartoon_url = 'http://'.$domain.$url_str;
				
				//dump($cartoon_url);
				$this->sendtemplateinfo($item["domain"], "@".$item["nickname"]."  ".$_POST["title"], $_POST["remark"], $_POST["novel_info"], $_POST["update_date"], $cartoon_url, $item["open_id"]);
			}
			//未选择用户的情况下
		}else{
			$user_list = D("user")->field("open_id,nickname,domain")->select();
			foreach($user_list as $key=>$item){
				$domain = $item["domain"];
				$url = $_POST['novel_url'];
				$url_start = strpos($url,'/Home');
				$url_str = substr($url,$url_start);
				$cartoon_url = 'http://'.$domain.$url_str;
				//echo $cartoon_url."<br>";
				$this->sendtemplateinfo($domain, "@".$item["nickname"]."  ".$_POST["title"], $_POST["remark"], $_POST["novel_info"], $_POST["update_date"], $cartoon_url, $item["open_id"]);
			}
		}
		
		echo "the end";
	}
	
	
	
	
	/**
     * 推送小说模板信息
     * */
    protected function sendtemplateinfo($domain, $title, $remark, $cartoon_info, $update_date, $cartoon_url, $open_id){
        $map["domain"] = $domain;
		$map['is_put'] = 1;
        $platform = D("platform")->where($map)->find();
		//dump($map);dump($domain);dump($title);die;
		$put_template_id = $platform['put_template_id'];
		if(!empty($put_template_id)){
				if(intval($platform["out_time"]) > time())	{
				$token = getWeChatToken($platform["appid"],$platform["secret"],$platform["token"]);
				}
				else{
					$token = getWeChatToken($platform["appid"],$platform["secret"]);
				}
				$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$token";
				$data = '{
						   "touser":"'.$open_id.'",
						   "template_id":"'.$put_template_id.'",
						   "url":"'.$cartoon_url.'",       
						   "data":{
							   "first": {
								   "value":"'.$title.'",
								   "color":"#ff1122"
							   },
							   "keyword1":{
								   "value":"'.$cartoon_info.'",
								   "color":"#173177"
							   },
							   "keyword2": {
								   "value":"'.$update_date.'",
								   "color":"#173177"
							   },
							   "remark":{
								   "value":"'.$remark.'",
								   "color":"#ff1122"
							   }
						   }
						}';   
						return $result = weChatCurl($url, 1, $data);
		}
        
        		
        
    }
	
	
	public function lst()
	{
		//获得所有公众号平台
		$platform_list = D("platform")->select();
		$this->assign("platform_list",$platform_list);
		$p = $_GET["p"] ? $_GET["p"] : 1;

		//查询条件
		if(!empty($_GET["nickname"])) {
			$map["nickname"] = array("like","%".$_GET["nickname"]."%");
			$this->assign("search_name",$_GET["nickname"]);
		}
		if(!empty($_GET["domain"])){
			$map["domain"] = $_GET["domain"];
			$this->assign("domain",$_GET["domain"]);
		}

		$novel = M('user');
		$pagesize = 50;#每页数量
		$offset = $pagesize * ($p - 1);//计算记录偏移量

		$count = $novel->where($map)->count();
		$list = $novel->where($map)->order("addtime desc")->limit($offset . ',' . $pagesize)->select();
		foreach($list as $key=>$item){
			$rs = D("platform")->field("platform_name")->where("domain='".$item["domain"]."'")->find();
			$list[$key]["platform_name"] = $rs["platform_name"];

			//获得历史记录
			$map["open_id"] = $item["open_id"];
			$hi_rs = D("read_history")->where($map)->order($map)->order("addtime desc")->find();
			if(!empty($hi_rs))
				$list[$key]["history"] = $hi_rs["novel_name"]." ".$hi_rs["chapter"]." <a href='/Home/Novel/show/id/".$hi_rs["chapter_id"]."/novel_id/".$hi_rs["novel_id"]."'>".$hi_rs["chapter_name"]."</a>";
		}

		$page = new \Think\Page($count, $pagesize);
		$page = $page->show();
		$this->assign('list', $list);
		$this->assign('page', $page);
		$this->display();
	}
	
	/**
	 * 多图文
	 * */
	public function sendInfoAll()
	{
		set_time_limit(0);
		$datas = $_POST;
		if (empty($datas)) {
			$this->error('请添加数据','lst');
		}
		$sum = count($datas['title']);
		if ($sum > 8) {
			$this->error('图文条数不能超过8条','lst');
		}
		addlog("推送多图文消息开始");
		//遍历数组
		$dataAll =[];
		for ($i=0; $i < $sum; $i++) {
			 // 上传缩略图片的url
			foreach($datas as $v){
				$dataAll[$i] = [
					'title' => $datas['title'][$i],
					'description' => $datas['description'][$i],
					'url' => $datas['url'][$i],
					'picurl' => $datas['picurl'][$i]
				];
			}
		}
		// var_dump($dataAll);die;
		// 将数组转为json数组
		$jsondata = json_encode($dataAll,JSON_UNESCAPED_UNICODE);
		$datanews = '{
			"articles": '.$jsondata.'
		}';
		$user_id = $datas['user_ids'];
		if(!empty($user_id)){
			$map["user_id"] = array("in", $user_id);
			$map['domain'] = $_POST['domain'];
			$map['subscribe'] = 1;
			$list = D("user")->where($map)->field('open_id')->select();
			foreach ($list as $key=>$item){
				$re = $this->sendimgpart($map['domain'],$datanews,$item["open_id"]);
			};	
		}else{
			$map['domain'] = $_POST['domain'];
			$map['subscribe'] = 1;
			$count = D("user")->where($map)->field('open_id')->count();
			for ($i = 0; $i < $count; $i++) {
				$item = D("user")->where($map)->field('open_id')->limit($i,1)->select();
				$re = $this->sendimgpart($map['domain'],$datanews,$item[0]['open_id']);
			}
			// $list = D("user")->where($map)->field('open_id')->select();
			// foreach ($list as $key=>$item){
			// 	$re = $this->sendimgpart($map['domain'],$datanews,$item["open_id"]);
			// };	
		}
		addlog("推送多图文消息结束");
		echo "the end";die;
	}
	/**
	 * 群发图文接口(发送给指定的人)
	 * */
	protected function sendimgpart($domain,$datanews,$open_id)
	{
		// 获取token
		$map['domain'] =$domain;
		$platform = D("platform")->where($map)-> find();
		if(intval($platform["out_time"]) > time())	{
			$token = getWeChatToken($platform["appid"],$platform["secret"],$platform["token"]);
		}else{
			$token = getWeChatToken($platform["appid"],$platform["secret"]);
		}
		$lasturl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$token";
		$data = '{
				    "touser":"'.$open_id.'",
				    "msgtype":"news",
				    "news":'.$datanews.'
				}
		';
		return $result = weChatCurl($lasturl,1,$data);
	}
	
	
	/**
	 * 关注书币推送模板信息
	 * */
	public function xin_send_info(){
		set_time_limit(0);
		$user_id = $_POST["user_ids"];
		$now_time = date('Y-m-d',time());
		
		$row = D('activity')->where("type = 3 and status = 1 and start_time <= '$now_time' and end_time >= '$now_time'")->find();	
		
		$time = $row['start_time'].'至'.$row['end_time'];
		
		if(!empty($user_id)){			
			$map["user_id"] = array("in", $user_id);
			$map['subscribe'] = 1;
			$list = D("user")->where($map)->select();
			//dump($list);die;
			foreach ($list as $key=>$item){
				//推送新生活影音关注推送活动
				if($item['domain'] == 'www.qichezuoyi.com.cn'){				
					//dump($_POST['title']);die;
					$this->sendtemplateinfo1($item["domain"], "@".$item["nickname"]."  ".$_POST["title"], $item["open_id"],$item["nickname"],$time);
				}elseif($item['domain'] == 'qikaism.cn'){
					$this->sendtemplateinfozuiquan1($item["domain"], "@".$item["nickname"]."  ".$_POST["title"], $item["open_id"],$item["nickname"],$time);
					
				}
				
			}
		}
		else{			
			$arr['subscribe'] = 1;
			$list = D('user')->where($arr)->select();			
			
			foreach ($list as $key=>$item){
				if($item['domain'] == 'www.qichezuoyi.com.cn'){
					$this->sendtemplateinfo1($item["domain"], "@".$item["nickname"]."  ".$_POST["title"], $item["open_id"],$item["nickname"],$time);
				}			
			}
		}

		echo "the end";
	}
	
	
	
	/**
	  *推送最全小说关注推送活动
	  */
	protected function sendtemplateinfozuiquan($domain, $title,$open_id,$nickname,$time){

		$map["domain"] = $domain;
		$platform = D("platform")->where($map)->find();

		if(intval($platform["out_time"]) > time())	{
			$token = getWeChatToken($platform["appid"],$platform["secret"],$platform["token"]);
		}
		else{
			$token = getWeChatToken($platform["appid"],$platform["secret"]);
		}
		//dump($token);die;
		//$token = "uE8o4BowpwHdc732mj869AkKGtrVB0Dumi1Hyu_ifLeSVNILA9Yyt1ZfXKJ8P3FpqPk7zYTEKUwD29O4gTAcoVs_NlY070ytewXeqran8iXXGeMLuzug58Sn3X9H2qVJHWXaACAVKL";
		//$openid = "ols0swsTiYZAdF6cdXxvTJqOWWCk";

		$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$token";
		$data = '{
		           "touser":"'.$open_id.'",
		           "template_id":"uU6EqdenkoEWB3HD1KNuboVUBz1f2mCedgOk5TN4MGc",
		           "url":"http://qikaism.cn/Home/Index/index",
		           "data":{
	                   "first": {
	                       "value":"'.$title.'",
	                       "color":"#173177"
	                   },
	                   "keyword1":{
	                       "value":"'.$nickname.'",
	                       "color":"#173177"
	                   },
	                    "keyword2": {
	                       "value":"推荐新用户关注获书币活动",
	                       "color":"#173177"
	                   },
	                   "keyword3": {
	                       "value":"'.$time.'",
	                       "color":"#173177"
	                   },
	                   "keyword4": {
	                       "value":"最全小说",
	                       "color":"#173177"
	                   },
	                   "remark":{
	                       "value":"点击查看详情",
	                       "color":"#173177"
	                   }
		           }
				}';
		$result = weChatCurl($url, 1, $data);
		//print_r($result);
	}
	
	
	
	
		/**
	  *推送最全小说关注推送活动
	  */
	protected function sendtemplateinfozuiquan1($domain, $title,$open_id,$nickname,$time){

		$map["domain"] = $domain;
		$platform = D("platform")->where($map)->find();

		if(intval($platform["out_time"]) > time())	{
			$token = getWeChatToken($platform["appid"],$platform["secret"],$platform["token"]);
		}
		else{
			$token = getWeChatToken($platform["appid"],$platform["secret"]);
		}
		//dump($token);die;
		//$token = "uE8o4BowpwHdc732mj869AkKGtrVB0Dumi1Hyu_ifLeSVNILA9Yyt1ZfXKJ8P3FpqPk7zYTEKUwD29O4gTAcoVs_NlY070ytewXeqran8iXXGeMLuzug58Sn3X9H2qVJHWXaACAVKL";
		//$openid = "ols0swsTiYZAdF6cdXxvTJqOWWCk";

		$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$token";
		$data = '{
		           "touser":"'.$open_id.'",
		           "template_id":"uU6EqdenkoEWB3HD1KNuboVUBz1f2mCedgOk5TN4MGc",
		           "url":"http://yimingshe.double-life.top/Home/Index/index&proxy_open_id='.$open_id.'",
		           "data":{
	                   "first": {
	                       "value":"'.$title.'",
	                       "color":"#173177"
	                   },
	                   "keyword1":{
	                       "value":"'.$nickname.'",
	                       "color":"#173177"
	                   },
	                    "keyword2": {
	                       "value":"推荐新用户关注获书币活动",
	                       "color":"#173177"
	                   },
	                   "keyword3": {
	                       "value":"'.$time.'",
	                       "color":"#173177"
	                   },
	                   "keyword4": {
	                       "value":"最全小说",
	                       "color":"#173177"
	                   },
	                   "remark":{
	                       "value":"点击查看详情",
	                       "color":"#173177"
	                   }
		           }
				}';
		$result = weChatCurl($url, 1, $data);
		//print_r($result);
	}
	
	/**
	 * 推送活动关注送书币模板信息
	 * */
	protected function sendtemplateinfo1($domain, $title,$open_id,$nickname,$time){

		$map["domain"] = $domain;
		$platform = D("platform")->where($map)->find();

		if(intval($platform["out_time"]) > time())	{
			$token = getWeChatToken($platform["appid"],$platform["secret"],$platform["token"]);
		}
		else{
			$token = getWeChatToken($platform["appid"],$platform["secret"]);
		}
		//dump($token);die;
		//$token = "uE8o4BowpwHdc732mj869AkKGtrVB0Dumi1Hyu_ifLeSVNILA9Yyt1ZfXKJ8P3FpqPk7zYTEKUwD29O4gTAcoVs_NlY070ytewXeqran8iXXGeMLuzug58Sn3X9H2qVJHWXaACAVKL";
		//$openid = "ols0swsTiYZAdF6cdXxvTJqOWWCk";

		$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$token";
		$data = '{
		           "touser":"'.$open_id.'",
		           "template_id":"Yvs72x8zwHFgUvA_0iNEmVUcQWRs7YvoE5PNzevxpsc",
		           "url":"http://yimingshe.double-life.top/Home/Index/index&proxy_open_id='.$open_id.'",
		           "data":{
	                   "first": {
	                       "value":"'.$title.'",
	                       "color":"#173177"
	                   },
	                   "keyword1":{
	                       "value":"'.$nickname.'",
	                       "color":"#173177"
	                   },
	                    "keyword2": {
	                       "value":"推荐新用户关注获书币活动",
	                       "color":"#173177"
	                   },
	                   "keyword3": {
	                       "value":"'.$time.'",
	                       "color":"#173177"
	                   },
	                   "keyword4": {
	                       "value":"新生活影音",
	                       "color":"#173177"
	                   },
	                   "remark":{
	                       "value":"点击查看详情",
	                       "color":"#173177"
	                   }
		           }
				}';
		$result = weChatCurl($url, 1, $data);
		//print_r($result);
	}
	
    public function url_test(){ 
    	$url = "https://www.baidu.com/";
    	$url = "https://m.emeixs.com/chapter/54/1/fromaid/159411962.html";
    	$cookie = "PHPSESSID=n10el0rvk9qgspneoqevq283r7; prid=0";
    	$header = fakeIp();
    	$content = getUrlContent($url, $header,$cookie, 1);
    	dump($content);
    }	
	
	/**
	 非阻塞推送
	 */
    public function threadputtemp(){

        //echo '111';die;
		$begin = time();
    	$data = $_POST;
    	//获取关注的用户的总条数
    	$count = D('user')->where("subscribe = 1")->count();
    	//除以600取余
    	if($count % $this->send_offset == 0)
    		$sum = $count / $this->send_offset;
    	else
    		$sum = intval($count / $this->send_offset) + 1;
    	//原来的代码
    	$url = "http://".$_SERVER[HTTP_HOST]."/User/processd.html";

		//小说地址分离域名
		$novel_url = $_POST["novel_url"];
		$url_start = strpos($novel_url,"/Home");
		$novel_url = substr($novel_url, $url_start, strlen($novel_url) - $url_start);			
		//循环创建进程
		for($i=0;$i<$sum;$i++) {
            D('test_result_copy1')->add(['result'=>$i]);
            //睡几秒
            if($i>=3) {
                if($i % 3 == 0) {
                    sleep(12);
                }
            }
		    //原来的代码
            //创建一个进程
			sock_post($url,["title"=>$_POST['title'],"remark"=>$_POST['remark'],"novel_info"=>$_POST['novel_info'],"update_date"=>$_POST['update_date'],"novel_url"=>$novel_url,"offset"=>$i * $this->send_offset]);
		}
		$end = time();
		echo "<meta charset='utf-8'>结束: 耗时".($end - $begin)."秒";
	}

    /**
     * 查找具体推送的用户
     */
	public function processd(){

    	$url = "http://".$_SERVER[HTTP_HOST]."/User/testsend.html";
   	//偏移量
		$offset = $_POST["offset"];
        D('test_result_copy')->add(['result' => $offset]);
        //睡几秒
		/*if($offset >= $this->send_offset * 10) {
            $sleep_time = intval($offset / ($this->send_offset * 10)) * 20;
            sleep($sleep_time);
        }*/

            //$rs = D("user")->field('open_id,domain,nickname')->where("subscribe=1 and nickname='没有名字'")->limit($offset,600)->select();
        //600一个循环推送
		$rs = D("user")->field('open_id,domain,nickname')->where("subscribe=1")->limit($offset,$this->send_offset)->select();

		if(!empty($rs)) {			
			foreach($rs as $key=>$item){
				//再次创建一个进程
				sock_post($url,[
					"domain"=>$item["domain"],
					"title"=>$_POST["title"],
					"remark"=>$_POST["remark"],
					"novel_info"=>$_POST["novel_info"], 
					"update_date"=>$_POST["update_date"], 
					"novel_url"=>"http://".$item["domain"].$_POST["novel_url"],
					"open_id"=>$item["open_id"],
					"nickname"=>$item['nickname']
				]);
			}
		}

	}

	/**
	 * 推送模板信息
	 * */
	public function testsend(){


          $data['nickname'] = $_POST['nickname'];
		  $data['open_id'] = $_POST['open_id'];
		  $data['domain'] = $_POST['domain'];
		  D('test_result')->add($data);
		  die;
			
//		$domain = $_POST["domain"];
//		$title = $_POST["title"];
//		$remark = $_POST["remark"];
//		$novel_info = $_POST["novel_info"];
//		$update_date = $_POST["update_date"];
//		$novel_url = $_POST["novel_url"];
//		$open_id = $_POST["open_id"] ? $_POST["open_id"] : "or28-0gHYXdyzKE91LcpV7NI2ytM";
//		$nickname = $_POST['nickname'] ? $_POST['nickname'] : "秋秋";
//
//		$map["domain"] = $domain;
//        $platform = D("platform")->where($map)->find();
//		$put_template_id = $platform['put_template_id'];
//		if(!empty($put_template_id)){
//			if(intval($platform["out_time"]) > time())	{
//				$token = getWeChatToken($platform["appid"],$platform["secret"],$platform["token"]);
//			}
//			else{
//				$token = getWeChatToken($platform["appid"],$platform["secret"]);
//			}
//		}
//		else{
//			die;
//		}
//		//echo 'end';die;
//		$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$token";
//		$data = '{
//		           "touser":"'.$open_id.'",
//		           "template_id":"'.$put_template_id.'",
//		           "url":"'.$novel_url.'",
//		           "data":{
//	                   "first": {
//	                       "value":"'.$title.'",
//	                       "color":"#ff1122"
//	                   },
//	                   "keyword1":{
//	                       "value":"'.$novel_info.'",
//	                       "color":"#173177"
//	                   },
//	                   "keyword2": {
//	                       "value":"'.$update_date.'",
//	                       "color":"#173177"
//	                   },
//	                   "remark":{
//	                       "value":"'.$remark.'",
//	                       "color":"#ff1122"
//	                   }
//		           }
//				}';
//		$result = weChatCurl($url, 1, $data);
//		if ($result['errcode'] == '40003' || $result['errcode'] == '43004') {
//			$d['subscribe'] = 0;
//			$re = M('user')->where("open_id= '$open_id'")->save($d);
//		}
//		$datas['errcode'] = $result['errcode'];
//		$datas['errmsg'] = $result['errmsg'];
//		$datas['open_id'] = $open_id;
//		$datas['domain'] = $domain;
//		$datas['nickname'] = $nickname;
//		$datas['result'] = $result;
//		$datas['addtime'] = time();
//		$res = M('test_result')->data($datas)->add();
	}
	
	
	
	
	// 更新推送
	public function updatepush()
	{
		$begin = time();
		// 查询今日更新的小说
    	$today = date("Y-m-d")." 00:00:00";
		$info = D("novel_chapter")->where("add_time >= '{$today}'")->field('content',true)->group("novel_id")->select();
		$sock_url = "http://".$_SERVER['HTTP_HOST']."/User/threadupdatepush.html";
		foreach ($info as $novel) {
			 sock_post($sock_url,$novel);
		}
		$end = time();
		echo "<meta charset='utf-8'>结束: 耗时".($end - $begin)."秒";
	
	}	

	/**
     * 更新推送模板消息
     */
    public function threadupdatepush(){
    	$data = $_POST;
    	$novel_id = $data['novel_id'];
    	// 查询历史记录
        $history = D("read_history")->field("open_id,max(addtime)")->group('open_id')->select();
	     foreach ($history as $v) {
	     	$map['open_id'] = $v['open_id'];
	     	$map['addtime'] = $v['max(addtime)'];
	     	// 最后阅读的小说
	     	$re = D("read_history")->field("open_id,novel_id,novel_name,addtime")->where($map)->find();

	     	$his_open = $re['open_id'];
            $domain_arr = D('user')->where("open_id='$his_open' and subscribe=1")->find();
            $domain = $domain_arr['domain'];
            $sock_url = "http://".$_SERVER['HTTP_HOST']."/user/testsend.html";
            if ($re['novel_id'] == $novel_id) {
            	sock_post($sock_url,[
		            "domain"=>$domain,
		            "title"=>'《' . $data['novel_name'] . '》更新到第' . $data['order_set'] . '章 ' . $data['title'],
		            "remark"=>'请您点击详情',
		            "novel_info"=>$data['novel_name'], 
		            "update_date"=>$data['add_time'], 
		            "novel_url"=>'http://' . $domain . '/Home/Novel/show/id/' . $data['id'] . '/novel_id/' . $data['novel_id'],
		            "open_id"=>$his_open,
		        ]);
            }
	     } 
    }
	/**
	 非阻塞推送图文
	 */
    public function threadsendinfo(){
		$begin = time();
		set_time_limit(0);
    	$data = $_POST;
    	$count = D('user')->where("subscribe = 1")->count();  	
    	if($count % 300 == 0)
    		$sum = $count / 300;
    	else
    		$sum = intval($count / 300) + 1;
		// $sum = 1;
    	$sock_url = "http://".$_SERVER[HTTP_HOST]."/User/thread_send_info.html";	
    	//小说地址分离域名
		$novel_url = $_POST["url"];
		$url_start = strpos($novel_url,"/Home");
		$novel_url = substr($novel_url, $url_start, strlen($novel_url) - $url_start);	
		for($i=0;$i<$sum;$i++) {
			sock_post($sock_url,["user_ids"=>$_POST['user_ids'],"title"=>$_POST['title'],"desc"=>$_POST['desc'],"img"=>$_POST['img'],"url"=>$novel_url,"offset"=>$i * 300]);
		}
		addlog("推送了单图文消息");
		$end = time();
		echo "<meta charset='utf-8'>结束: 耗时".($end - $begin)."秒";
	}

	/**
	 * 非阻塞服务号推送图文信息
	 * */
	public function thread_send_info(){
		set_time_limit(0);
		$user_id = $_POST["user_ids"];
		$sock_url = "http://".$_SERVER[HTTP_HOST]."/User/sendimgs.html";
		$offset = $_POST["offset"];
		if(!empty($user_id)){
			$map["user_id"] = array("in", $user_id);
			$map['subscribe'] = 1;
			// $map['nickname'] = "lovesoar";
            //获取关注了的用户
			$list = D("user")->where($map)->field("open_id,domain,nickname")->limit($offset,300)->select();
			foreach ($list as $key=>$item){
			    //新生活影音推送图文信息
                sock_post($sock_url,[
                	"domain"=>$item["domain"],
                	"title"=>"@".$item["nickname"]." ".$_POST["title"],
                	"desc"=>$_POST['desc'],
                	"url"=>'http://'.$item["domain"].$_POST['url'],
                	"img"=>$_POST['img'],
                	"open_id"=>$item['open_id']
                ]);
            }
		}else{
			$map["subscribe"] = 1;
			// $map['nickname'] = array('in',["lovesoar","王溪"]);
			$list = D("user")->field("open_id,domain,nickname")->where($map)->limit($offset,300)->select();
			foreach ($list as $key=>$item){
               sock_post($sock_url,[
               	"domain"=>$item["domain"],
               	"title"=>"@".$item["nickname"]." ".$_POST["title"],
               	"desc"=>$_POST['desc'],
               	"url"=>'http://'.$item["domain"].$_POST['url'],
               	"img"=>$_POST['img'],
               	"open_id"=>$item['open_id']
               ]);				
			}
		}
	}

	/**
	 * 非阻塞群发图文接口
	 * @domain 用户针对的域名,判断用户是哪个公众号的
	 * @title 图文标题 @description 描述
	 * @url 连接地址
	 * @picurl 图片地址
	 * @open_id 用户OPEN_ID
	 * */
	public function sendimgs(){
		$domain = $_POST["domain"];
		$title = $_POST["title"];
		$description = $_POST["desc"];
		$_url = $_POST["url"];
		$picurl = $_POST["img"];
		$open_id = $_POST['open_id'];

		$map["domain"] = $domain;		
		$platform = D("platform")->where($map)->find();
		if(intval($platform["out_time"]) > time())	{
			$token = getWeChatToken($platform["appid"],$platform["secret"],$platform["token"]);
		}
		else{
			$token = getWeChatToken($platform["appid"],$platform["secret"]);
		}
		
		$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$token";
		$data = '{
				    "touser":"'.$open_id.'",
				    "msgtype":"news",
				    "news":{
				        "articles": [
					         {
					             "title":"'.$title.'",
					             "description":"'.$description.'",
					             "url":"'.$_url.'",
					             "picurl":"'.$picurl.'"
					         }
				         ]
				    }
				}
		';
		$result = weChatCurl($url, 1, $data);
	}
	
	// 订阅号推送图文（非阻塞）
	public function subscribesendinfo(){
		set_time_limit(0);
		$begin = time();
	   $platform_id = $_POST['platform_id'];
	   $data = $_POST;
	   //文艺街拍
	   if($platform_id == '10'){
	   		$this->subscribe_get_openid($platform_id,$data);
	        addlog("推送了文艺街拍单图文消息");
		   echo 'the  end';die;
		   //经典语语录
       }elseif ($platform_id == '11'){
           $this->subscribe_get_openid($platform_id,$data);
		   addlog("推送了经典语语录单图文消息");
		   echo 'the  end';die;
        //起点相册
       }elseif($platform_id == '12'){
           $this->subscribe_get_openid($platform_id,$data);
		   addlog("推送了起点相册单图文消息");
		   echo 'the  end';die;
           //金典说说录
       }elseif ($platform_id == '13'){
           $this->subscribe_get_openid($platform_id,$data);
		   addlog("推送了金典说说录单图文消息");
		   echo 'the  end';die;
       }
       $end = time();
		echo "<meta charset='utf-8'>结束: 耗时".($end - $begin)."秒";
    }

    // 获取所有用户(订阅号推送用)
    protected function subscribe_get_openid($platform_id,$data)
    {
		$platform_arr = D('platform')->where("platform_id='$platform_id'")->find();
       //获取token
       if($platform_arr['out_time']>time()){
           $token = getWeChatToken($platform_arr["appid"],$platform_arr["secret"],$platform_arr["token"]);
       }else{
           $token = getWeChatToken($platform_arr["appid"],$platform_arr["secret"]);
       }
       $domain = $platform_arr['domain'];
       //得到token之后再获取用户列表
       $geturl = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$token.'&next_openid=';
       // 所有用户openid
       $openid_arr = $this->getopenid($geturl);
       // 获取关注用户总数
       $result =  weChatCurl($geturl, "get");
       $count = $result['total'];
       if($count % 300 == 0)
    		$sum = $count / 300;
       else
    		$sum = intval($count / 300) + 1;
    	// sock请求地址
    	$sock_url = "http://".$_SERVER['HTTP_HOST']."/User/subscribe_to.html";
    	$novel_url = $data["url"];
		$url_start = strpos($novel_url,"/Home");
		$novel_url = substr($novel_url, $url_start, strlen($novel_url) - $url_start);
    	for($i=0;$i<$sum;$i++) {
    		// 如果使用post传输openid_arr的话可能会传输两过大
			sock_post($sock_url,[
					"domain"=>$domain,
					"title"=>$data['title'],
					"desc"=>$data['desc'],
					"url"=>$novel_url,
					"img"=>$data['img'],
					"offset"=>$i*300,
					"openid_arr"=>$openid_arr
				]);
		}
      	
    }
    /**
     * [subscribe_to 订阅号推送中转]
     * @return [type]        [description]
     */
    public function subscribe_to()
    {
    	set_time_limit(0);
		$sock_url = "http://".$_SERVER[HTTP_HOST]."/User/sendimgs.html";
		$offset = $_POST["offset"];
		$openid_arr = $_POST['openid_arr'];
		$list = array_slice($openid_arr,0,300);
		foreach ($list as $open_id){
           sock_post($sock_url,[
           	"domain"=>$_POST["domain"],
           	"title"=>$_POST["title"],
           	"desc"=>$_POST['desc'],
           	"url"=>'http://'.$_POST["domain"].$_POST['url'],
           	"img"=>$_POST['img'],
           	"open_id"=>$open_id
           ]);				
		}
    }

    /**
     * 自动生成自定义菜单
     */
    public function menu(){
        $list = D('platform')->field('platform_name,domain,platform_id')->where('is_stock=0 and is_service = 1')->select();
        foreach($list as $key=>$value){
            $set_domain = $value['domain'];
            $count = D('domain')->field('show_domain')->where("set_domain = '$set_domain' and status = 0")->count();
            $list[$key]['count'] = $count;
        }
        $this->assign('list',$list);
        $this->display();
    }

    public function menuedit(){
        $platform_id = $_GET['id'];
        $platform = D('platform')->field('platform_name,domain,platform_id')->where("platform_id = $platform_id")->find();
        $this->assign('platform',$platform);
        $this->display('form');
    }


    public function menuupdate(){
        $platform = D('platform')->field('domain')->where("platform_id = ".$_POST['platform_id'])->find();
        $old_set_domain = $platform['domain'];
        $data['domain'] = $_POST['set_domain'];
        $set['set_domain'] = $_POST['set_domain'];
        D('platform')->where('platform_id = '.$_POST['platform_id'])->save($data);
        $domain_id = D('domain')->field('id')->where("set_domain = '$old_set_domain'")->select();
        foreach ($domain_id as $value){
            $id = $value['id'];
            D('domain')->where("id = $id")->save($set);
        }
        $this->createmenu($data['domain']);
        $this->success('生成菜单成功！');
        die;
    }

    public function menuadd()
    {
        if (!$_POST) {
            $platform_id = $_GET['id'];
            $this->assign('platform_id', $platform_id);
            $this->display('addshow');
            die;
        }
        //set_domain
        $id = $_POST['id'];
        $platform_id = intval($id);
        $platform = D('platform')->field('domain')->where("platform_id = $platform_id")->find();
        $set_domain = $platform['domain'];
        //show_domain
        $data['show_domain'] = isset($_POST['show_domain'][0]) ? $_POST['show_domain'][0] : '';
        if (ctype_space($data['show_domain'])) {
            $this->error('警告！域名必填项目。');
        }
        $domains = $data['show_domain'];
        $domains = trim($domains);
        $domain_a = explode("\r\n", $domains);
        $domain = array_filter($domain_a);
        foreach ($domain as $v) {
            $map['show_domain'] = trim($v);
            $map['set_domain'] = $set_domain;
            M('domain')->data($map)->add();
        }
        $this->success('添加落地成功', 'menu');
        die;
    }

    public function createmenu($domain){
        //echo $domain;
        //die;
        $where['domain'] = $domain;
        $set_domain = $domain;
        //将原来的绑定域名拿到
        //到数据库中去查
        $platform_arr = D('platform')->where($where)->find();
        $old_token = $platform_arr['token'];
        if(intval($platform_arr["out_time"]) > time())	{
            $access_token = getWeChatToken($platform_arr["appid"],$platform_arr["secret"],$platform_arr["token"]);
        }
        else{
            $access_token = getWeChatToken($platform_arr["appid"],$platform_arr["secret"]);
        }

        if($access_token == $old_token){
            $access_token = getWeChatToken($platform_arr["appid"],$platform_arr["secret"]);
        }
        //dump($access_token);die;
        //菜单
        //新版本自动生成菜单
        $jsonmenu = '{
				  "button":[
				   {	
						"type":"view",
						"name":"阅读记录",
						"url":"http://'.$set_domain.'/Home/Shelf/myhistory"
				   },
				   {	
						"type":"view",
						"name":"书城首页",
						"url":"http://'.$set_domain.'/Home/Index/index"
				   },
				   {
					   "name":"用户中心",
					   "sub_button":[		   
					   {
						   "type":"view",
						   "name":"个人中心",
						   "url":"http://'.$set_domain.'/Home/User/userinfo"
						},
						{
						   "type":"view",
						   "name":"我要充值",
						   "url":"http://'.$set_domain.'/Home/User/recharge"
						},
						{
							 "type":"click",
							 "name":"联系客服",
							 "key":"link"
						}]   
				   }
				   ]
					}';
        //生成旧版本的菜单
        /*$jsonmenu = '{
              "button":[
              {   
                     "type":"view",
                     "name":"阅读记录",
                 "url":"http://jcyrdjf.cn/Home/Novel/readhistory"
              },
              {   
                     "type":"view",
                     "name":"书城首页",
                 "url":"http://jcyrdjf.cn/Home/Index/index"
              },
               {
                   "name":"用户中心",
                   "sub_button":[        
                 {
                       "type":"view",
                       "name":"个人中心",
                       "url":"http://jcyrdjf.cn/Home/User/index"
                    },
                    {
                       "type":"view",
                       "name":"赠送书币",
                       "url":"http://jcyrdjf.cn/Home/User/getbookmoney"
                    },
                    {
                       "type":"view",
                       "name":"我要充值",
                       "url":"http://jcyrdjf.cn/Home/User/recharge"
                    },
                    {
                         "type":"click",
                     "name":"联系客服",
                     "key":"link"
                    }]
               
        
               }]
         }';*/
        /*{
            "type":"view",
						   "name":"赠送书币",
						   "url":"http://'.$set_domain.'/Home/User/getbookmoney"
						},*/
        //dump($jsonmenu);
        //dump($access_token);die;

        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
        $result = weChatCurl($url, 1, $jsonmenu);
        if($result['errcode'] == 0){
            echo "恭喜您,自定义菜单成功";
        }else{
            echo '若绑定死掉，注意微信公众号的配置';
            $error = $result['errmsg'];
            $this->error('错误提示:'.$error);
        }

        //将绑定域名传过来
        //然后丢到自定义菜单中
        //访问以下自定义菜单方法
        //更改数据库的绑定域名
        //完成

    }


    //生成media_id
    public function media_id()
    {
        $this->display();
    }
    public function media_id1(){
        $files = $_FILES;
        dump($files);
        //$access_token = 'mDLWZw0m1lMRg4K834iRtUnkKFlJ8NR3WdTs_gXodiX-n5ycK4sRo-6-iYVmjeSp3PZ9cclYtv1JFkOjc38-KAYqBgOdXtipqL-V4DB_mFX1ENwMHPg1AnnRrwAdsMGrNRMeAGAIMH';
        $access_token = $_POST['access_token'];
        $url = 'https://api.weixin.qq.com/cgi-bin/material/add_material?access_token='.$access_token.'&type=image';
        $res = api_img($url,$files);
        $res1 = json_decode($res);
        dump($res1);

    }


    public function testy(){
        header("Content-type: text/html; charset=utf-8");

        //echo 111;die;
        //$res = D('order')->field('sum(money) as total_money,open_id')->where('status=1 and sum(money) >= 10000')->select();
        echo '循环数量:'.D('test_result_copy1')->count();echo '<br>';
        echo '偏移数量:'.D('test_result_copy')->count();echo '<br>';
        echo '推的结果:'.D('test_result')->count();echo '<br>';
        echo '关注的用户数:'.D('user')->where('subscribe=1')->count();echo '<br>';
        //dump(D('test_result')->where('errcode != 0 and errcode != 48004')->select());




        //echo intval('2.6');


    }




}